import {getaxios} from './request.js';

export function parseQuery(url) {
    var queryObj = {};
    var reg = /[?&]([^=&#]+)=([^&#]*)/g;
    var querys = url.match(reg);
    if (querys) {
        // for (var i in querys) {
        for (var i = 0; i < querys.length; i++) {
            if (querys[i]) {
                var query = querys[i].split('=');
            }
            var key = query[0].substr(1),
                value = query[1];
            // queryObj[key] ? queryObj[key] = [].concat(queryObj[key], value) : queryObj[key] = value;
            queryObj[key] ? queryObj[key] = queryObj[key] : queryObj[key] = value;
            if (!(queryObj[key]) || queryObj[key] == "undefined" || queryObj[key] == "(null)" || queryObj[key] == "null") {
                queryObj[key] = "";
            } else {
                queryObj[key] = queryObj[key]
            }
        }
    } else {
        queryObj["token"] = "";
    }
    return queryObj;
}

export function openApp(url, todetail) {
    // 获取安卓下载连接
    getaxios(TESTAPI + "/index/getSysList", {
            "type": "0002",
            "serviceType": "000200001"
    }).then(function (res) {
        if (res.data.status == "200") {
            config["down_Adr"] = res.data.data[0].attribute1
        }
        return Promise.resolve(res.data);
    }).catch(function (err) {
        return err;
    });

    var config = {
        // //scheme:必须
        scheme_IOS: 'dingyiapp://share?',
        scheme_Adr: "dw://com.dingyi.duowei/openapp?",
        down_IOS: DownIos,
        // down_IOS: "https://itunes.apple.com/us/app/%E5%A4%9A%E7%BB%B4/id1295030161?l=zh&ls=1&mt=8",
        timeout: 500
    };
    var startTime = Date.now();
    // 用户点击时，在动态创建一个iframe，并且让这个iframe去加载config中的Schema
    // var ifr = document.createElement('iframe');
    window.location.href = ISIOS ? config.scheme_IOS + todetail : config.scheme_Adr + todetail;
    // ifr.style.display = 'none';
    // document.body.appendChild(ifr);

    var t = setTimeout(function () {
        var endTime = Date.now();
        //指定的时间内没有跳转成功 当前页跳转到apk的下载地址
        if ((endTime - startTime) < (config.timeout + 500)) {
            //判断是否在微信和qq端打开
            if (isWeixinQq == "weixin") {
                window.location.href = url + "&brofrom=true&" + todetail
            } else {
                // window.location.href = "download.html?"+todetail;
                window.location.href = ISIOS ? config.down_IOS : config.down_Adr;
            }
        } else {
            window.close();
        }
    }, config.timeout);

    window.onblur = function () {
        clearTimeout(t);
    }
}